<template>
  <div>
    <change-password ref="passRef" />

    <el-dropdown @command="handleCommand" @visible-change="handleVisibleChange">
      <span class="avatar-dropdown">
        <el-avatar class="user-avatar" :src="avatar" />
        <div class="username">
          <span class="hidden-xs-only">{{ name ? name : '管理员' }}</span>
          <vab-icon class="vab-dropdown" :class="{ 'vab-dropdown-active': active }" icon="arrow-down-s-line" />
        </div>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="clear_cache">
            <vab-icon icon="refresh-line" />
            <span>{{ translate('更新缓存') }}</span>
          </el-dropdown-item>
          <el-dropdown-item command="change_password">
            <vab-icon icon="lock-password-line" />
            <span>{{ translate('更换密码') }}</span>
          </el-dropdown-item>
          <el-dropdown-item command="logout">
            <vab-icon icon="logout-circle-r-line" />
            <span>{{ translate('退出登录') }}</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script lang="ts" setup>
import { clear_cache } from '/@/api/user'
import { translate } from '/@/i18n'
import { useUserStore } from '/@/store/modules/user'
import { toLoginRoute } from '/@/utils/routes'

defineOptions({
  name: 'VabAvatar',
})

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const { avatar, name } = storeToRefs(userStore)
const { logout } = userStore
const active = ref<boolean>(false)
const passRef = ref<any>(null)
const $baseMessage = inject<any>('$baseMessage')

const handleVisibleChange = (value: boolean) => {
  active.value = value
}
const handleCommand = async (command: any) => {
  switch (command) {
    case 'logout':
      //退出登录
      await logout()
      await router.push(toLoginRoute(route.fullPath))
      break
    case 'change_password':
      //修改密码
      passRef.value.showDialog()
      break
    case 'clear_cache':
      //清除缓存
      clear_cache().then((res: any) => {
        $baseMessage(res.msg, 'success', 'hey')
      })
      break
  }
}
</script>

<style lang="scss" scoped>
.avatar-dropdown {
  display: flex;
  align-content: center;
  align-items: center;
  justify-content: center;
  justify-items: center;

  .user-avatar {
    box-sizing: border-box;
    width: 40px;
    height: 40px;
    padding: 0px;
    margin-left: 15px;
    cursor: pointer;
    border-radius: 50%;
  }

  .username {
    position: relative;
    display: flex;
    align-content: center;
    align-items: center;
    width: max-content;
    height: 40px;
    margin-left: 6px;
    line-height: 40px;
    cursor: pointer;

    [class*='ri-'] {
      margin-left: 0 !important;
    }
  }
}
</style>
